package com.open.cloud.rbac.service.orgpost.impl;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.open.cloud.rbac.entity.orgpost.CoreOrganization;
import com.open.cloud.rbac.entity.orgpost.CoreUserOrgRel;
import com.open.cloud.rbac.mapper.orgpost.CoreOrganizationMapper;
import com.open.cloud.rbac.mapper.orgpost.CoreUserOrgRelMapper;
import com.open.cloud.rbac.object.orgpost.CoreOrganizationDto;
import com.open.cloud.rbac.object.orgpost.CoreOrganizationSelectDto;
import com.open.cloud.rbac.object.orgpost.CoreOrganizationVo;
import com.open.cloud.rbac.service.orgpost.ICoreOrganizationService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 组织架构 服务实现类
 * </p>
 *
 * @author wangzengzhou01
 * @since 2024-12-23
 */
@Service
public class CoreOrganizationServiceImpl extends ServiceImpl<CoreOrganizationMapper, CoreOrganization>
        implements ICoreOrganizationService {

    @Resource
    private CoreOrganizationMapper organizationMapper;

    @Resource
    private Snowflake snowflake;

    @Resource
    private CoreUserOrgRelMapper userOrgRelMapper;

    /**
     * 新增组织架构
     *
     * @param organizationDto
     * @return
     */
    @Override
    public JSONObject createOrganizationInfo(CoreOrganizationDto organizationDto) {
        CoreOrganization organization = new CoreOrganization();
        BeanUtils.copyProperties(organizationDto, organization);
        organization.setId(snowflake.nextIdStr());
        organization.setCreateTime(new Date());
        organization.setUpdateTime(new Date());
        int i = organizationMapper.insert(organization);
        JSONObject result = new JSONObject();
        if (i > 0) {
            result.put("code", 200);
            result.put("message", "创建成功");
        } else {
            result.put("code", 500);
            result.put("message", "创建失败");
        }
        return result;
    }

    /**
     * 修改组织架构
     *
     * @param organizationDto
     * @return
     */
    @Override
    public JSONObject updateOrganizationInfo(CoreOrganizationDto organizationDto) {
        CoreOrganization organization = new CoreOrganization();
        BeanUtils.copyProperties(organizationDto, organization);
        organization.setUpdateTime(new Date());
        int i = organizationMapper.updateById(organization);
        JSONObject result = new JSONObject();
        if (i > 0) {
            result.put("code", 200);
            result.put("message", "修改成功");
        } else {
            result.put("code", 500);
            result.put("message", "修改失败");
        }
        return result;
    }

    /**
     * 根据组织Id删除
     *
     * @param organizationId
     * @return
     */
    @Override
    public JSONObject deleteOrganizationInfo(String organizationId) {
        LambdaQueryWrapper orgRelQuery = Wrappers.<CoreUserOrgRel>lambdaQuery()
                .eq(CoreUserOrgRel::getOrgId, organizationId);
        List orgRelList = userOrgRelMapper.selectList(orgRelQuery);
        JSONObject result = new JSONObject();
        if (orgRelList.size() > 0) {
            result.put("code", 500);
            result.put("message", "该部门组织下存在用户，无法删除");
        } else {
            int i = this.baseMapper.deleteById(organizationId);
            if (i > 0) {
                result.put("code", 200);
                result.put("message", "删除成功");
            } else {
                result.put("code", 500);
                result.put("message", "删除失败");
            }
        }
        return result;
    }

    /**
     * 分页查询组织
     *
     * @param orgSelectDto
     * @return
     */
    @Override
    public IPage<CoreOrganization> selectOrganizationPage(CoreOrganizationSelectDto orgSelectDto) {
        LambdaQueryWrapper queryWrapper = Wrappers.<CoreOrganization>lambdaQuery()
                .eq(ObjectUtils.isNotEmpty(orgSelectDto.getCompanyId()), CoreOrganization::getCompanyId, orgSelectDto.getCompanyId())
                .orderByDesc(CoreOrganization::getSort);
        IPage<CoreOrganization> page = new Page<>(orgSelectDto.getPageNo(), orgSelectDto.getPageSize());
        IPage data = this.baseMapper.selectPage(page, queryWrapper);
        return data;
    }

    /**
     * 查询部门组织树列表
     *
     * @param orgSelectDto
     * @return
     */
    @Override
    public List<CoreOrganizationVo> selectOrganizationTree(CoreOrganizationSelectDto orgSelectDto) {
        LambdaQueryWrapper queryWrapper = Wrappers.<CoreOrganization>lambdaQuery()
                .eq(ObjectUtils.isNotEmpty(orgSelectDto.getCompanyId()), CoreOrganization::getCompanyId, orgSelectDto.getCompanyId())
                .orderByDesc(CoreOrganization::getSort);
        List list = this.baseMapper.selectList(queryWrapper);
        List result = getOrgVoList(list, "0", "", 0);
        return result;
    }

    private List<CoreOrganizationVo> getOrgVoList(List<CoreOrganization> list, String parentId, String parentName, Integer level) {
        List<CoreOrganizationVo> resultList = new ArrayList<>();
        Integer currentLevel = level;
        list.forEach(item -> {
            if (item.getPId().equals(parentId)) {
                CoreOrganizationVo organizationVo = new CoreOrganizationVo();
                organizationVo.setParentOrgName(parentName);
                organizationVo.setLevel(currentLevel);
                BeanUtils.copyProperties(item, organizationVo);
                List<CoreOrganizationVo> children = getOrgVoList(list, item.getId(), item.getOrgName(), currentLevel + 1);
                organizationVo.setChildren(children);
                resultList.add(organizationVo);
            }
        });
        return resultList;
    }

    /**
     * 查询部门组织列表
     *
     * @param orgSelectDto
     * @return
     */
    @Override
    public List<CoreOrganization> selectOrganizationList(CoreOrganizationSelectDto orgSelectDto) {
        LambdaQueryWrapper queryWrapper = Wrappers.<CoreOrganization>lambdaQuery()
                .eq(ObjectUtils.isNotEmpty(orgSelectDto.getCompanyId()), CoreOrganization::getCompanyId, orgSelectDto.getCompanyId())
                .orderByDesc(CoreOrganization::getSort);
        List list = this.baseMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 根据companyId查询orgId
     *
     * @param companyId
     * @return
     */
    @Override
    public List<String> selectOrgIdsByCompanyId(String companyId) {
        List<String> data = organizationMapper.selectOrgIds(companyId);
        return data;
    }

}
